package com.idanchuang.component.provider;

import com.idanchuang.component.provider.config.InterceptorConfig;
import com.idanchuang.component.provider.config.RpcConfig;
import com.idanchuang.component.provider.interceptor.RpcInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
@EnableDiscoveryClient
public class ProviderAutoConfiguration {

    @Bean("idanchuangProviderRpcConfig")
    @ConfigurationProperties(prefix = "idanchuang.component.provider.rpc")
    public RpcConfig rpcConfig() {
        return new RpcConfig();
    }

    @Bean("idanchuangProviderInterceptorConfig")
    @ConfigurationProperties("idanchuang.component.provider.rpc.interceptor")
    public InterceptorConfig interceptorConfig() {
        return new InterceptorConfig();
    }

    @Bean
    @ConditionalOnMissingBean(name = "acgRpcInterceptor")
    public RpcInterceptor acgRpcInterceptor(RpcConfig rpcConfig) {
        return new RpcInterceptor(rpcConfig);
    }

    @Bean
    public WebMvcConfigurer abmRpcMvcConfigurer(RpcInterceptor rpcInterceptor, InterceptorConfig interceptorConfig) {
        return new WebMvcConfigurer() {
            /**
             * 拦截器配置
             * @param registry 拦截器注册器
             */
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                if (interceptorConfig.isEnabled()) {
                    // 权限拦截
                    registry.addInterceptor(rpcInterceptor)
                            .addPathPatterns(interceptorConfig.getIncludes())
                            .excludePathPatterns(interceptorConfig.getExcludes());
                }
            }
        };
    }

}
